package com.sens.orderback.ui.activity.mybank;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sens.common.DeviceUtil;
import com.sens.commonui.PermissionUtil;
import com.sens.database.LiteOrmDBUtil;
import com.sens.orderback.OrderBackApplication;
import com.sens.orderback.R;
import com.sens.orderback.ui.base.BaseFragment;
import com.sens.tables.MybankConfig;
import com.sens.utils.FloatWindowManager;
import com.sens.utils.MybankTestHelper;
import com.sens.utils.ToastUtil;

public class MybankFragment extends BaseFragment {
    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_mybank_main, null);
    }

    @Override
    public void onFirstUserVisible() {
        titleTV = findViewById(R.id.titleTV);
        scrollView = findViewById(R.id.scrollView);
        textView = findViewById(R.id.textView);
        toogleTV = findViewById(R.id.toogleTV);
        findViewById(R.id.goSetting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goSetting(view);
            }
        });
        findViewById(R.id.history).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                history(view);
            }
        });
        findViewById(R.id.clearLog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearLog(view);
            }
        });
        findViewById(R.id.test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                test(view);
            }
        });
        toogleTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toogle(view);
            }
        });
        initTestHelper();
        if (PermissionUtil.checkOverlaysPermission(getContext())) {
            showFloat();
        } else {
            PermissionUtil.requestOverlaysPermissions(getContext(), new PermissionUtil.OnPermissionCallback() {
                @Override
                protected void onGranted() {
                    showFloat();
                }
            });
        }
    }

    private void showFloat() {
        FloatWindowManager.createFloatWindow(getContext(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toogle(v);
            }
        });
    }

    private ScrollView scrollView;
    private TextView textView;
    private TextView titleTV;
    private TextView toogleTV;

    private MybankTestHelper mybankTestHelper;

    private Runnable scrollRunnable = new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    };
    private boolean hasDeviceId = false;
    private boolean hasDatabase = false;

    private boolean initTestHelper() {
        if (!hasDeviceId)
            DeviceUtil.getDeviceId(getActivity(), new DeviceUtil.OnDeviceIdCallback() {
                @Override
                protected void onDeviceIdCallback(String deviceId) {
                    hasDeviceId = true;
                    titleTV.setText(DeviceUtil.getSystemModel() + ":" + deviceId);
                }
            });
        if (!hasDatabase)
            if (!PermissionUtil.checkPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                PermissionUtil.requestPermissions(getActivity(), new PermissionUtil.OnPermissionCallback() {
                    @Override
                    public void onGranted() {
                        if (!hasDatabase) initDatabase();
                    }
                }, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            } else initDatabase();
        return hasDeviceId && hasDatabase;
    }

    private void initDatabase() {
        hasDatabase = true;
        OrderBackApplication.getInstance().initDatabase();
        mybankTestHelper = new MybankTestHelper(getActivity(), new MybankTestHelper.NoticeLogListener() {
            @Override
            public void noticeLog(CharSequence message) {
                textView.setText(message);
                scrollView.postDelayed(scrollRunnable, 100);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mybankTestHelper != null)
            mybankTestHelper.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        initTestHelper();
        mybankConfig = LiteOrmDBUtil.getGlobalDBUtil(getContext().getApplicationContext()).queryOne(MybankConfig.class);
        if (isStart == mybankConfig.isStart()) return;
        isStart = mybankConfig.isStart();
        changeView();
    }

    @Override
    public void onPause() {
        if (mybankTestHelper != null) mybankTestHelper.saveLog();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        if (mybankTestHelper != null) mybankTestHelper.unBind();
        scrollView = null;
        textView = null;
        titleTV = null;
        mybankTestHelper = null;
        scrollRunnable = null;
        super.onDestroy();
    }

    public void goSetting(View view) {
        startActivity(new Intent(getActivity(), SettingActivity.class));
    }

    public void history(View view) {
        startActivity(new Intent(getActivity(), ListActivity.class));
    }

    public void clearLog(View view) {
        if (!initTestHelper()) return;
        if (mybankTestHelper != null) mybankTestHelper.clearLog();
    }

    public void test(View view) {
        if (!initTestHelper()) return;
        if (mybankTestHelper != null) mybankTestHelper.startTest();
    }

    private MybankConfig mybankConfig;

    private boolean isStart;

    public void toogle(View view) {
        mybankConfig = LiteOrmDBUtil.getGlobalDBUtil(getContext().getApplicationContext()).queryOne(MybankConfig.class);
        if (!isStart && !mybankConfig.isCollectionAble()) {
            ToastUtil.showToast("检测未通过，暂不能开启");
            return;
        }
        isStart = !isStart;
        if (isStart) {
            mybankConfig.setStart(true);
            if (mybankTestHelper != null) mybankTestHelper.getHandle().start();
        } else {
            mybankConfig.setStart(false);
            if (mybankTestHelper != null) mybankTestHelper.getHandle().stop();
        }
        changeView();
        LiteOrmDBUtil.getGlobalDBUtil(getContext().getApplicationContext()).update(mybankConfig);
    }

    private void changeView() {
        if (isStart) {
            toogleTV.setText("已开启");
            toogleTV.setBackgroundColor(0xFF00AA00);
        } else {
            toogleTV.setText("已关闭");
            toogleTV.setBackgroundColor(0xFFFF0000);
        }
        FloatWindowManager.toogle(isStart);
    }
}
